package com.javabaas.server.novel_server.book.service;

import com.javabaas.server.novel_server.book.entity.*;
import com.javabaas.server.novel_server.common.Constant;
import com.javabaas.server.novel_server.common.ModuleCode;
import com.javabaas.server.novel_server.common.ResponseJson;
import com.javabaas.server.novel_server.common.StatusCode;
import com.javabaas.server.novel_server.exception.ServiceException;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class BookService {

    @Autowired
    BookBodyRepository repository;

    @Autowired
    BookRepository bookRepository;

    @Autowired
    RecommendBookRepository recommendBookRepository;

    @Autowired
    MongoTemplate mongoTemplate;


    private final Logger logger = Logger.getLogger(getClass());


    /**
     *获取书籍的更新信息
     */
    public Object update(HttpServletRequest request) {
        String books = request.getParameter("books");
        if (books == null) {
            throw new ServiceException(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_BOOKS_EMPTY);
        }
        String[] ids = books.split(",");
        List<Book> res_books = new ArrayList<>();
        for (String id: ids) {
            Book bk = bookRepository.findBy_idIsLike(id);
            if (bk != null) {
                res_books.add(bk);
            }
        }

        return ResponseJson.getResponseJson(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_OK, res_books);
    }


    /**
     * 推荐的书籍
     *
     * 查询某本书籍的推荐书籍
     */
    public Object recommendBooks(HttpServletRequest request) {
        String bookId = request.getParameter("bookId");
        if (StringUtils.isEmpty(bookId)) {
            throw new ServiceException(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_BOOKID_EMPTY);
        }
        RecommendBook recommendBook = recommendBookRepository.findByBookId(bookId);
        if (recommendBook.getRecommendBooks().size() > 0) {
            logger.info("recommendBooks-->" + recommendBook.getRecommendBooks());
            List<Book> books = bookRepository.findBy_idIsIn(recommendBook.getRecommendBooks());
            for (String id: recommendBook.getRecommendBooks()) {
                Book bk = bookRepository.findBy_idIsLike(id);
                if (bk != null) {
                    books.add(bk);
                }
            }
            return ResponseJson.getResponseJson(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_OK, books);
        }else {
            return ResponseJson.getResponseJson(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_OK);
        }
    }


    /**
     * 搜索书籍列表(minor 分类搜索)
     *
     */
    public Object categories(HttpServletRequest request) {
        String type = request.getParameter("type");
        String gender = request.getParameter("gender");
        String pageStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("pageSize");
        String major = request.getParameter("major");
        if (StringUtils.isEmpty(StringUtils.trimAllWhitespace(major)) || StringUtils.isEmpty(type)) {
            throw new ServiceException(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_MAIOR_TEXT_EMPTY);
        }
        int page = 0;
        int pageSize = Constant.PAGE_SIZE_MAX;
        if (!StringUtils.isEmpty(pageStr)) {
            page = Integer.parseInt(pageStr);
        }
        if (!StringUtils.isEmpty(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr);
            pageSize =  Math.min(pageSize, Constant.PAGE_SIZE_MAX);
        }
        Sort sort = new Sort(Sort.Direction.DESC, "latelyFollower");
        PageRequest pageRequest = new PageRequest(page, pageSize, sort);

        List<Book> books = bookRepository.findByGenderContainsAndTypeAndMajorCate(gender, type ,major, pageRequest);
        return ResponseJson.getResponseJson(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_OK, books);
    }


    /**
     *搜索书籍列表
     *
     * 参数type: 1 title, 2 tag, 3 auth, 4 title & auth
     */
    public Object searchBookList(HttpServletRequest request) {
        String typeStr = request.getParameter("type");
        String pageStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("pageSize");
        String s = request.getParameter("s");
        int type = 0;
        int page = 0;
        int pageSize = Constant.PAGE_SIZE_MAX;
        if (StringUtils.isEmpty(StringUtils.trimAllWhitespace(s))) {
            throw new ServiceException(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_SEARCH_TEXT_EMPTY);
        }
        if (!StringUtils.isEmpty(typeStr)) {
            type = Integer.parseInt(typeStr);
        }
        if (!StringUtils.isEmpty(pageStr)) {
            page = Integer.parseInt(pageStr);
        }
        if (!StringUtils.isEmpty(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr);
            pageSize =  Math.min(pageSize, Constant.PAGE_SIZE_MAX);
        }
        //参数1表示当前第几页,参数2表示每页的大小,参数3表示排序
        PageRequest pageRequest = new PageRequest(page, pageSize);
        List<Book> books = new ArrayList<>();

        if (type == 1) {
            books = bookRepository.findByTitleContainsOrderByLatelyFollowerDesc(s, pageRequest);
        } else if (type == 2) {
            books = bookRepository.findByTagsIsContainingOrderByLatelyFollowerDesc(s, pageRequest);
        } else if (type == 3) {
            books = bookRepository.findByAuthorContainsOrderByLatelyFollowerDesc(s, pageRequest);
        }else if (type == 4) {
            books = bookRepository.findByTitleContainsOrAuthorContainsOrderByLatelyFollowerDesc(s, s, pageRequest);
        }
        return ResponseJson.getResponseJson(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_OK, books);
    }


    /**
     * 获取某个rank下的书籍列表
     *
     * @param rankId 排行榜id
     *
     * type: 1 rank/ 2 monthRank/ 3 totalRank
     */
    public Object getBookList(HttpServletRequest request, String rankId) {
        int type = 1;
        int page = 0;
        int pageSize = Constant.PAGE_SIZE_MAX;
        String typeString = request.getParameter("type");
        String pageStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("pageSize");
        if (!StringUtils.isEmpty(typeString)) {
            type = Integer.parseInt(typeString);
        }
        if (!StringUtils.isEmpty(pageStr)) {
            page = Integer.parseInt(pageStr);
        }
        if (!StringUtils.isEmpty(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr);
            pageSize =  Math.min(pageSize, Constant.PAGE_SIZE_MAX);
        }
        List<Book> books = new ArrayList<>();
        Sort sort = new Sort(Sort.Direction.DESC, "latelyFollower");
        //参数1表示当前第几页,参数2表示每页的大小,参数3表示排序
        PageRequest pageRequest = new PageRequest(page, pageSize, sort);

        if (type == 1) {
            books = bookRepository.findByRankId(rankId, pageRequest);
        }else if (type == 2) {
            books = bookRepository.findByMonthRank(rankId, pageRequest);
        }else if (type == 3) {
            books = bookRepository.findByTotalRank(rankId, pageRequest);
        }
        return ResponseJson.getResponseJson(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_OK, books);
    }


    /**
     * 获取指定书籍的某一章节内容
     *
     * @param bookId 书籍id
     *
     * @param index 书籍章节
     */
    public Object body(String bookId, Integer index) {
        if (StringUtils.isEmpty(bookId)) {
            throw new ServiceException(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_BOOKID_EMPTY);
        }
        BookBody bookBody = repository.findByBookAndIndexEquals(bookId, index);
        return ResponseJson.getResponseJson(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_OK, bookBody);
    }


    /**
     * 下载书籍的内容
     *
     * @param bookId 书籍ID
     *
     * @param page 分页
     *
     * @param pagesize 每页大小
     *
     */
    public Object downloadBookBodys(String bookId, Integer page, Integer pagesize) {
        if (StringUtils.isEmpty(bookId)) {
            throw new ServiceException(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_BOOKID_EMPTY);
        }
        Sort sort = new Sort(Sort.Direction.ASC, "index");
        PageRequest pageRequest = new PageRequest(page, pagesize, sort);
        List<BookBody> bookBodyList = repository.findByBook(bookId, pageRequest);
        return ResponseJson.getResponseJson(ModuleCode.MODULE_BOOK_STATUS, StatusCode.STATUS_OK, bookBodyList);
    }





}
